<?php
/*
 * Created on 2012-3-30
 *
 * To change the template for this generated file go to
 * Window - Preferences - PHPeclipse - PHP - Code Templates
 */
 class Tongji_model extends CI_Model{
 	private $_date ;
 	public function __construct()
 	{
 		$this->load->database();
 		$this->load->library('session');
 		$this->load->library('Tools');
 		$this->load->model('anti_model');
 		$this->_date = date("Y-m-d");
 	}
	/*
	 * 获取登录用户的信息
	 */
	 public function getUserInfo()
	 {
		$result = array();
		$result['username'] = $this->session->userdata('user_name');
		$result['userid'] = $this->session->userdata('user_id');
		$result['area'] = $this->session->userdata('area');
		$result['note'] = $this->session->userdata('note');
		$result['lashLogin'] = date('Y-m-d',$this->session->userdata('last_login'));
		$result['lastIp'] = $this->session->userdata('last_ip');
		$result['integral'] = $this->session->userdata('integral');//积分
		$result['add_date'] = date('Y-m-d',$this->session->userdata('add_time'));//注册时间
		return $result;
	 }
	/**
	 * 获取注册网站信息
	 */
	 public function getUserWebsite()
	 {
	 	$sql = "select * from tj_website where uid=".$this->session->userdata('uid');
	 	$query = $this->db->query($sql);
		$arr = $query->result_array();
		$website_arr = array();
		foreach($arr as $kk=>$vv)
		{
			$arr['data'][] = $vv;
			$arr['vist_count'][$vv['wid']] = $this->redisinit->get('website_'.$vv['uid'].'_'.$vv['wid']);
			$website_arr['websiteList'][$vv['wid']] = $vv;
		}
		return $arr;
	 }

	 /*
	  * 获取选择网站信息
	  */
	public function getWebSiteInfo()
	{
		$wid = filter_input(INPUT_GET, 'wid', FILTER_SANITIZE_SPECIAL_CHARS);
		if($this->session->userdata('wid') && empty($wid))
		{
			return;
		}else{
			if($wid<1)
			{
				$this->tools->showMessage("非法操作",'back');
			}
			$where = " where uid=".$this->session->userdata('uid')." and wid=".$wid;
			$sql = " select * from tj_website ".$where;
			$query = $this->db->query($sql);
			$arr = $query->row_array();
			if($arr){
				$this->session->set_userdata($arr);
			}else{
				$this->tools->showMessage("非法操作",'back');
			}
		}
	}

	/*
	 * 统计概况
	 */
	 public function gaikuang($sday=null)
	 {
	 	$where = " where wid=".$this->session->userdata('wid');
		$wid = $this->session->userdata('wid');
		if($sday)
		{
			//当天PV
			$pv = $this->redisinit->llen($this->config->item('stat').$wid."::".$sday);
			if($pv)
			{
				//当天访客
				$dayvister = $this->redisinit->hlen($this->config->item('dayvister').$sday."::".$wid);
				//当天独立访客
				$indevister = $this->redisinit->hlen($this->config->item('indevister').$sday."::".$wid);

				//当天ip
				$dayip = $this->redisinit->scard($this->config->item('dayip').$sday."::".$wid);
				$avg_searchTimes = round($pv/$dayvister,2);
				$data[$sday] = array('total_arrives'=>$pv,'total_vids'=>$dayvister,'total_ips'=>$dayip,'total_isnew'=>$indevister,'avg_searchTimes'=>$avg_searchTimes);
				return $data;
			}
		}else{
			//查询总的
			$total_arrives = $this->redisinit->get($this->config->item('stat').$wid);
			$total_vids = $this->redisinit->hlen($this->config->item('vister').$wid);
			$dayip = $this->redisinit->scard($this->config->item('ip').$wid);
			$avg_searchTimes = round($total_arrives/$total_vids,2);
			$data = array('total_arrives'=>$total_arrives,'total_vids'=>$total_vids,'total_ips'=>$dayip,'total_isnew'=>$total_vids,'avg_searchTimes'=>$avg_searchTimes);
			return $data;
		}

		return null;

	 }

	/*
	 * 今日访问明细
	 */
	 public function DayData($sday=null,$eday=null,$days=null)
	 {
	 	$int_sdate = strtotime($sday);
	 	if(empty($eday))
			$int_edate = strtotime($sday);
		else
			$int_edate = strtotime($eday." +1 day");

		$wid = $this->session->userdata('wid');
		for($i=1;$i<=$days;$i++)
		{
			$day = date('Y-m-d',strtotime($sday." +".$i." day"));
			$data = $this->redisinit->lrange($this->config->item('stat').$wid."::".$day,0,-1);
			foreach($data as $v)
			{
				$arr[] = json_decode($v);
			}
		}


		$data = array();
		$total = array();
		$date_total = array();
		$tmp_ip = array();
		$tmp_vid = array();
		$tmp_newvid = array();
		$tmp_key = array();
		$total_pv = 0;
		$date_tmp_ip = array();
		$date_tmp_vid = array();
		$date_tmp_newvid = array();
		$date_total_pv = array();
		$today = strtotime(date('Y-m-d'));
		foreach($arr as $kk=>$vv)
		{

			$key = date('Y-m-d',$vv->arriveTime);

			if($vv->firstTime>=$today)
			$vv->isnew = 1;
			$data[date('H',$vv->arriveTime).':00'][] = $vv;
			$date_tmp_ip[$key][] = $vv->ip;
			$date_tmp_vid[$key][] = $vv->vid;
			$tmp_key[] = $key;

			$tmp_ip[$key][] = $vv->ip;
			$tmp_vid[$key][] = $vv->vid;


			if($vv->firstTime>=$int_sdate)
			{
				$date_tmp_newvid[$key][] = $vv->vid;
			}
			$total_pv +=1;
			@$date_total_pv[$key] +=1;
		}

		$tmp_key = array_unique($tmp_key);
		foreach($tmp_key as $k=>$v)
		{
			$date_total[$v]['pv'] = $date_total_pv[$v];
			$date_total[$v]['ips'] = sizeof(array_unique($tmp_ip[$v]));
			$date_total[$v]['vids'] = sizeof(array_unique($tmp_vid[$v]));
			$date_total[$v]['newVids'] = @sizeof(array_unique($tmp_newvid[$v]));
			$date_total[$v]['avg_arriveTimes'] = 0;
			if($date_total[$v]['vids']>0){
				$date_total[$v]['avg_arriveTimes'] = round($date_total_pv[$v]/$date_total[$v]['vids'],2);
			}
		}


		$day_hour = $this->tools->day_hour();
		$result = array();

		foreach($day_hour as $dh)
		{
			$result[$dh[0]."-".$dh[1]]=array();
			$result[$dh[0]."-".$dh[1]]['newVid'] = 0;
			$result[$dh[0]."-".$dh[1]]['isbad'] = 0;
			$result[$dh[0]."-".$dh[1]]['arriveCount'] =0;
			$result[$dh[0]."-".$dh[1]]['stopTime'] = 0;
			$result[$dh[0]."-".$dh[1]]['arriveTimes'] = 0;
			$result[$dh[0]."-".$dh[1]]['ave_stopTime'] = 0;
			$result[$dh[0]."-".$dh[1]]['intent'] = 0;
			$result[$dh[0]."-".$dh[1]]['ips'] = 0;
			$result[$dh[0]."-".$dh[1]]['vids'] = 0;
			$result[$dh[0]."-".$dh[1]]['ave_arriveCount'] =0;
			$result[$dh[0]."-".$dh[1]]['bili'] = 0;




			$tmp_ip = array();
			$tmp_vid = array();
			$tmp_newvid = array();

			foreach($data as $kk=>$vv)
			{
				if($kk>=$dh[0] && $kk<$dh[1]){

					foreach($vv as $k=>$v)
					{
						if($v->firstTime>=$int_sdate)
						{
							$tmp_newvid[] = $v->vid;
						}

						$result[$dh[0]."-".$dh[1]]['stopTime'] += $v->stopTime;
						//@$result[$dh[0]."-".$dh[1]]['arriveTimes'] = $vid_arriveCount[$v['vid']];
						$tmp_ip[] = $v->ip;
						$tmp_vid[] = $v->vid;
					}
					$result[$dh[0]."-".$dh[1]]['arriveCount'] = sizeof($vv);

					$result[$dh[0]."-".$dh[1]]['ips'] = sizeof(array_unique($tmp_ip));
					$result[$dh[0]."-".$dh[1]]['vids'] = sizeof(array_unique($tmp_vid));
					$result[$dh[0]."-".$dh[1]]['newVid'] = sizeof(array_unique($tmp_newvid));
					$result[$dh[0]."-".$dh[1]]['ave_arriveCount'] = round($result[$dh[0]."-".$dh[1]]['arriveCount']/$result[$dh[0]."-".$dh[1]]['vids'],2);
					$result[$dh[0]."-".$dh[1]]['bili'] = round ($result[$dh[0]."-".$dh[1]]['arriveCount']*100/$total_pv,2);
				}
			}
		}

		$xml = $this->make_xml($result);
		$result_arr = array();
		$result_arr['total'] = $total;
		$result_arr['data'] = $result;
		$result_arr['xml'] = $xml;
		$result_arr['date_total'] = $date_total;
		return $result_arr;
	 }

	/*
	 * 产生xml文件
	 */
	 function make_xml($data)
	 {


	 	$day_hour = $this->tools->day_hour();
	 	$day_hour_arr = array();
		$day_hour_arr['pv']['00:00'] = 0;
		$day_hour_arr['ip']['00:00'] = 0;
		$day_hour_arr['访客']['00:00'] = 0;
		$day_hour_arr['新访客']['00:00'] = 0;
	 	foreach($day_hour as $k=>$v)
	 	{
	 		$day_hour_arr['pv'][$v[1]]=$data[$v[0]."-".$v[1]]['arriveCount'];
			$day_hour_arr['ip'][$v[1]]=$data[$v[0]."-".$v[1]]['ips'];
			$day_hour_arr['访客'][$v[1]]=$data[$v[0]."-".$v[1]]['vids'];
			$day_hour_arr['新访客'][$v[1]]=$data[$v[0]."-".$v[1]]['newVid'];
	 	}
		array_unshift($day_hour,array('00:00','00:00'));
	 	$str = '<?xml version="1.0" charset="utf8"?>';
		$str .= '<chart bgAlpha="10,10" bgAngle="270" bgColor="FFFFFF,CC3300" chartRightMargin="35" numvdivlines="5" labelStep="2" shadowAlpha="40" alternateHGridColor="CC3300" alternateHGridAlpha="5" showAlternateHGridColor="1" divLineIsDashed="1" divLineColor="CC3300" divLineAlpha="20" anchorRadius="2" formatNumberScale="0" showValues="0" lineThickness="1" caption="小时段"> ' ;
		$str .='<categories>';
		foreach($day_hour as $kk=>$vv)
		{
			$str .='<category label="'.$vv[1].'"/>';
		}
		$str .='</categories>';
		foreach($day_hour_arr as $kk => $vv)
		{

			$color = $this->tools->rand_color();
			$str .= '<dataset seriesName="'.$kk.'" color="'.$color.'">';
			foreach($vv as $key=>$val)
			{
				$str .='<set label="'.$key.'" value="'.$val.'"/>';
			}
			$str .='</dataset>';
		}

		$str .='<styles> -<definition> <style size="12" type="font" name="CaptionFont"/> </definition> -<application> <apply styles="CaptionFont" toObject="CAPTION"/> <apply styles="CaptionFont" toObject="SUBCAPTION"/> </application> ' ;
		$str .='</styles></chart>';

		return $str;
	 }
	/**
	 * 保存网站信息
	 */
	 public function save_website()
	 {
		 $insert_data = array();
		 $insert_data['wName'] = $this->input->post('wName');
		 $insert_data['wUrl'] = $this->input->post('wUrl');
		 $insert_data['wAddTime'] = time();
		 $insert_data['wType'] = $this->input->post('sType');
		 $insert_data['wDomain'] = $this->input->post('wDomain');
		 $insert_data['wProvince'] = $this->input->post('province');
		 $insert_data['wCity'] = $this->input->post('city');
		 $insert_data['uid'] = $this->session->userdata('uid');
		 $this->db->insert('tj_website',$insert_data);
		 $wid = $this->db->insert_id();
		 self::getUserWebsite();
		 $data = $this->tools->default_setting($wid);
		 $this->db->insert('tj_setting', $data);
		 $this->anti_model->setWebSettingData($wid);
		 $this->anti_model->setWebData($this->session->userdata('uid'),$wid);
		 return true;
	 }

	/**
	 * 受访域名来路列表
	 * $sdate 开始时间；$edate 结束时间
	 * $type: 1：来路域名url   2:受访页面url   默认：来路域名url＋受访页面url
	 * $top:展示前多少条
	 */
	 public function top_url($sdate,$edate,$type=null,$top=5)
	 {
	 	$limit = "";
	 	if($top)
	 		$limit .=" limit 5";
		$where =" where arriveTime>=".strtotime($sdate) ." and arrivetime<=".strtotime($sdate.'+1 day')." and wid=".$this->session->userdata('wid');
		$sql = "select refer_domain,arriverefer from tj_stat ".$where." group by refer_domain,arriverefer ".$limit;
		$query = $this->db->query($sql);
		$arr = $query->result_array();
		$result = $refer_domain = $arriverefer = array();
		foreach($arr as $k=>$v)
		{
			if($v['refer_domain'])
				$refer_domain[] = $v['refer_domain'];
			if($v['arriverefer'])
				$arriverefer[] = $v['arriverefer'];
		}
		if(count($refer_domain)>0)
			$refer_domain = array_count_values($refer_domain);
		if(count($arriverefer)>0)
			$arriverefer = array_count_values($arriverefer);
		if($type==1)
			return  $refer_domain;
		else if($type == 2)
			return 	$arriverefer;
		else{
			return array(
					'refer_domain'=>$refer_domain,
					'arriverefer'=>$arriverefer,
			);
		}
	 }

	 /*
	  * 区域统计图
	  */
	  public function top_area($sdate,$edate,$type=null)
	  {
	  	$where = " where wid=".$this->session->userdata('wid')." and arriveTime>=".strtotime($sdate)." and arriveTime<=".strtotime($edate." +1 day") ." and city!=''";
	  	$sql = " select count(*) as area_count,city from tj_stat ".$where." group by city ORDER BY area_count desc limit 10 ";

	  	$query = $this->db->query($sql);
		$arr = $query->result_array();
		return self::make_top_area_xml($arr);
	  }

	  public function make_top_area_xml($data)
	  {
	  	$str = "<?xml version='1.0' charset='utf8'?>" .
	  			"<chart palette='2'>";
	  	foreach($data as $k=>$v)
	  	{
	  		$str .="<set label='".$v['city']."' value='".$v['area_count']."'  />";
	  	}

        $str .="</chart>";
        return $str;
	  }
 }
?>
